{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>智面未来</title>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.11.0/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/pose-detection@latest/dist/pose-detection.min.js"></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <!-- 确保在HTML中正确引入TensorFlow.js和MoveNet -->

    <!-- 放在 <head> 标签内或业务脚本之前 -->


  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            danger: '#FF5757',
            warning: '#FFAA33',
            neutral: '#F5F7FA',
            dark: '#1D2939'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .video-shadow {
        box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.1);
      }
      .btn-pulse {
        animation: pulse 2s infinite;
      }
      @keyframes pulse {
        0% {
          box-shadow: 0 0 0 0 rgba(22, 93, 255, 0.4);
        }
        70% {
          box-shadow: 0 0 0 10px rgba(22, 93, 255, 0);
        }
        100% {
          box-shadow: 0 0 0 0 rgba(22, 93, 255, 0);
        }
      }
      .fade-in {
        animation: fadeIn 0.5s ease-in-out;
      }
      @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
      }
      .slide-up {
        animation: slideUp 0.4s ease-out;
      }
      @keyframes slideUp {
        from { transform: translateY(20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
      }
      .direction-card {
        transition: all 0.3s ease;
      }
      .direction-card:hover {
        transform: translateY(-5px);
      }
      .behavior-hint {
        animation: fadeInOut 4s ease-in-out;
      }
      @keyframes fadeInOut {
        0%, 100% { opacity: 0; }
        10%, 90% { opacity: 1; }
      }
      .score-indicator {
        transition: width 0.5s ease;
      }
      .blink {
        animation: blink 1s infinite;
      }
      @keyframes blink {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
      }
      /* 笔试相关样式 */
      .exam-container {
        max-height: 70vh;
        overflow-y: auto;
      }
      .question-card {
        transition: all 0.3s ease;
        border-left: 4px solid #165DFF;
      }
      .question-card.correct {
        border-left: 4px solid #36D399;
      }
      .question-card.incorrect {
        border-left: 4px solid #FF5757;
      }
      .option-item {
        transition: all 0.2s ease;
      }
      .option-item:hover {
        transform: translateX(5px);
        background-color: #F0F5FF;
      }
      .option-item.selected {
        background-color: #E6F7FF;
        border: 1px solid #91D5FF;
      }
      .option-item.correct {
        background-color: #F6FFED;
        border: 1px solid #B7EB8F;
      }
      .option-item.incorrect {
        background-color: #FFF2F0;
        border: 1px solid #FFCCC7;
      }
      .progress-bar {
        height: 8px;
        border-radius: 4px;
        background-color: #E8EAEF;
        overflow: hidden;
      }
      .progress-fill {
        height: 100%;
        background-color: #165DFF;
        transition: width 0.5s ease;
      }
      .explanation {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.5s ease;
      }
      .explanation.show {
        max-height: 200px;
      }
        .behavior-hint {
    z-index: 100 !important; /* 确保在最上层 */
    transform: translateZ(0); /* 避免被其他元素遮挡 */
}
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">

  <!-- 导航栏 -->
  <nav id="main-nav" class="fixed w-full top-0 z-50 transition-all duration-300 py-4">
    <div class="container mx-auto px-4 md:px-6 lg:px-8">
      <div class="flex justify-between items-center">
        <a href="#" class="flex items-center space-x-2">
          <div class="w-10 h-10 bg-primary rounded-lg flex items-center justify-center">
            <i class="fa fa-comments text-white text-xl"></i>
          </div>
          <span class="text-xl font-bold text-primary">智面未来</span>
        </a>

        <!-- 桌面导航 -->
        <div class="hidden md:flex items-center space-x-6">
          <!-- 系统说明 -->
          <div class="relative group mr-6">
            <a href="#" class="text-dark hover:text-primary transition-colors font-medium flex items-center">
              系统说明 <i class="fa fa-chevron-down ml-1 text-xs transition-transform group-hover:rotate-180"></i>
            </a>
            <div class="absolute left-0 mt-2 w-48 bg-white rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 border border-gray-100">
              <a href="#business" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors">业务场景</a>
              <a href="#features" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors">功能需求</a>
              <a href="#technology" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors">技术架构</a>
            </div>
          </div>

          <!-- 模拟面试 -->
          <a href="/mnms/" class="text-dark hover:text-primary transition-colors font-medium">模拟面试</a>

          <!-- 笔试入口 -->
          <a href="#exam" id="exam-link" class="text-dark hover:text-primary transition-colors font-medium">技术笔试</a>

          <!-- 个人主页 -->
          <div class="relative group">
            <a href="#" class="text-dark hover:text-primary transition-colors font-medium flex items-center">
              {{ name }}的个人主页 <i class="fa fa-chevron-down ml-1 text-xs transition-transform group-hover:rotate-180"></i>
            </a>
            <div class="absolute right-0 mt-2 w-60 bg-white rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 border border-gray-100">
              <a href="/info/" class="block px-4 py-2 text-dark bg-primary/5 text-primary font-medium">个人信息</a>
              <a href="/changeinfo/" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors">修改个人信息</a>
              <a href="/msjl/" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors">面试记录</a>
              <div class="border-t border-gray-100 my-1"></div>
              <a href="#about" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors">关于我们</a>
              <a href="/login/" class="block px-4 py-2 text-dark hover:bg-primary/5 hover:text-primary transition-colors text-red-600">注销</a>
            </div>
          </div>

        </div>

        <!-- 移动端菜单按钮 -->
        <button id="menu-btn" class="md:hidden text-dark focus:outline-none">
          <i class="fa fa-bars text-2xl"></i>
        </button>
      </div>
    </div>

    <!-- 移动端导航菜单 -->
    <div id="mobile-menu" class="md:hidden hidden bg-white absolute w-full border-t border-gray-100">
      <div class="container mx-auto px-4 py-3 space-y-3">
        <a href="/mnms/" class="block text-dark hover:text-primary transition-colors py-2 font-medium">模拟面试</a>
        <a href="#exam" id="mobile-exam-link" class="block text-dark hover:text-primary transition-colors py-2 font-medium">技术笔试</a>

        <!-- 系统说明下拉菜单 -->
        <div class="mobile-dropdown">
          <button class="w-full text-left flex justify-between items-center text-dark hover:text-primary transition-colors py-2 font-medium">
            系统说明 <i class="fa fa-chevron-down text-xs transition-transform"></i>
          </button>
          <div class="mobile-dropdown-content hidden pl-4 pt-2 pb-3 space-y-2">
            <a href="#business" class="block text-dark hover:text-primary transition-colors py-1">业务场景</a>
            <a href="#features" class="block text-dark hover:text-primary transition-colors py-1">功能需求</a>
            <a href="#technology" class="block text-dark hover:text-primary transition-colors py-1">技术架构</a>
          </div>
        </div>

        <!-- 个人主页下拉菜单 -->
        <div class="mobile-dropdown">
          <button class="w-full text-left flex justify-between items-center text-dark hover:text-primary transition-colors py-2 font-medium">
            个人主页 <i class="fa fa-chevron-down text-xs transition-transform"></i>
          </button>
          <div class="mobile-dropdown-content hidden pl-4 pt-2 pb-3 space-y-2">
            <a href="#profile" class="block text-primary py-1 font-medium">个人信息</a>
            <a href="#edit-profile" class="block text-dark hover:text-primary transition-colors py-1">修改个人信息</a>
            <a href="/msjl/" class="block text-dark hover:text-primary transition-colors py-1">面试记录</a>

            <div class="border-t border-gray-100 my-1 w-2/3"></div>
            <a href="#about" class="block text-dark hover:text-primary transition-colors py-1">关于我们</a>
            <a href="#logout" class="block text-dark hover:text-primary transition-colors py-1 text-red-600">注销</a>
          </div>
        </div>

        <a href="#contact" class="block bg-primary text-white px-5 py-2 rounded-full text-center hover:bg-primary/90 transition-colors font-medium">了解更多</a>
      </div>
    </div>
  </nav>

  <!-- 主内容区 - 面试界面 -->
  <main id="interview-main" class="flex-grow container mx-auto px-4 py-8 md:py-12">
    <div class="max-w-7xl mx-auto">
      <!-- 标题区域 -->
      <div class="text-center mb-8 slide-up">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-2">技术岗位模拟面试</h1>
        <p class="text-gray-500">系统将实时分析您的面试表现并提供反馈</p>
      </div>

      <!-- 视频区域 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-10">
        <!-- 左侧面试官视频 -->
        <div class="relative rounded-xl overflow-hidden video-shadow bg-dark fade-in">
          <div id="interviewer-video-container" class="aspect-video relative">
            <!-- 面试官提问视频 -->
            <video id="interviewer-video" class="w-full h-full object-cover absolute inset-0" muted>
              <source src="{% static 'video/msg.mp4' %}" type="video/mp4">
              您的浏览器不支持视频标签
            </video>

            <!-- 面试官倾听视频 -->
            <video id="interviewer-listening-video" class="w-full h-full object-cover absolute inset-0 hidden" muted loop>
              <source src="{% static 'video/listen.mp4' %}" type="video/mp4">
              您的浏览器不支持视频标签
            </video>

            <!-- 初始状态提示 -->
            <div id="interview-waiting" class="absolute inset-0 bg-dark/70 flex flex-col items-center justify-center text-white">
              <i class="fa fa-play-circle text-5xl mb-4 text-primary/80"></i>
              <p class="text-center px-8">请点击"开始面试"按钮启动模拟面试</p>
            </div>

            <!-- 面试官状态指示器 -->
            <div id="interviewer-status" class="absolute bottom-4 left-4 bg-dark/60 text-white text-sm px-3 py-1 rounded-full flex items-center hidden">
              <span class="w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"></span>
              <span>等待您的回答</span>
            </div>

            <!-- 面试官倾听状态指示器 -->
            <div id="interviewer-listening-status" class="absolute bottom-4 left-4 bg-dark/60 text-white text-sm px-3 py-1 rounded-full flex items-center hidden">
              <span class="w-2 h-2 bg-blue-400 rounded-full mr-2 animate-pulse"></span>
              <span>正在倾听您的回答</span>
            </div>

            <!-- 问题显示区域 -->
            <div id="question-display" class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-dark/90 to-transparent p-6 text-white hidden">
              <h3 class="font-medium mb-1">当前问题:</h3>
              <p id="current-question" class="text-lg">请介绍一下您的项目经验，以及您在项目中担任的角色和贡献？</p>
            </div>
          </div>
          <div class="p-4 bg-white">
            <h3 class="font-semibold">李面试官</h3>
            <p class="text-sm text-gray-500">资深技术经理 · 5年面试经验</p>
          </div>
        </div>

        <!-- 右侧用户摄像头 -->
        <div class="relative rounded-xl overflow-hidden video-shadow bg-dark fade-in">
          <div id="user-video-container" class="aspect-video relative">
            <!-- 用户摄像头初始状态 -->
            <div id="camera-placeholder" class="absolute inset-0 bg-gray-800 flex flex-col items-center justify-center text-white">
              <i class="fa fa-video-camera text-5xl mb-4 text-gray-600"></i>
              <p class="text-center px-8">摄像头未启动</p>
              <p class="text-sm text-gray-400 mt-2">点击"开始面试"按钮启用摄像头</p>
            </div>

            <!-- 行为分析提示层 -->
            <div id="behavior-hints" class="absolute inset-0 pointer-events-none z-10 overflow-hidden">
              <!-- 提示信息将在这里动态生成 -->
            </div>

            <!-- 行为评分指示器 -->
            <div id="behavior-score-indicator" class="absolute top-4 left-4 bg-white/80 text-dark text-sm px-3 py-1 rounded-lg hidden">
              <div class="flex items-center mb-1">
                <span class="font-medium mr-2">行为评分:</span>
                <span id="current-score" class="font-bold">100</span>
              </div>
              <div class="w-full bg-gray-200 rounded-full h-2">
                <div id="score-bar" class="bg-primary h-2 rounded-full score-indicator" style="width: 100%"></div>
              </div>
                   <!-- 在行为评分指示器中增加情绪评分 -->
                <div id="behavior-score-indicator" class="absolute top-4 left-4 bg-white/80 text-dark text-sm px-3 py-1 rounded-lg hidden">
       <div class="flex items-center mb-1">
           <span class="font-medium mr-2">行为评分:</span>
           <span id="current-score" class="font-bold">100</span>
       </div>
       <div class="w-full bg-gray-200 rounded-full h-2">
           <div id="score-bar" class="bg-primary h-2 rounded-full score-indicator" style="width: 100%"></div>
       </div>
       <div class="mt-1">
           <span class="font-medium">情绪评分:</span>
           <span id="emotion-score" class="font-bold">70</span> <!-- 新增情绪评分显示 -->
       </div>
   </div>

            </div>

            <!-- Canvas用于绘制姿势检测结果 -->
            <canvas id="detection-canvas" class="absolute inset-0 z-5 hidden"></canvas>

            <!-- 用户摄像头视频流 -->
            <video id="user-video" class="w-full h-full object-cover hidden" autoplay muted playsinline></video>

            <!-- 摄像头加载状态 -->
            <div id="camera-loading" class="absolute inset-0 bg-dark/70 flex flex-col items-center justify-center text-white hidden">
              <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mb-4"></div>
              <p>正在启动摄像头...</p>
              <p class="text-sm mt-2">正在初始化行为分析系统</p>
            </div>

            <!-- 回答状态指示器 -->
            <div id="recording-indicator" class="absolute top-4 right-4 bg-red-500 text-white text-xs px-2 py-1 rounded-full flex items-center hidden">
              <span class="w-2 h-2 bg-white rounded-full mr-1 animate-pulse"></span>
              <span>正在录制</span>
            </div>
          </div>
          <div class="p-4 bg-white">
            <h3 class="font-semibold">您的实时画面</h3>
            <p class="text-sm text-gray-500">系统将分析您的表现并提供实时反馈</p>
          </div>
        </div>
      </div>

      <!-- 控制按钮区域 -->
      <div class="flex flex-col sm:flex-row items-center justify-center gap-4 md:gap-6 slide-up">
        <!-- 开始面试按钮 -->
        <button id="start-interview" class="bg-primary hover:bg-primary/90 text-white px-8 py-4 rounded-full font-medium transition-all shadow-lg hover:shadow-primary/30 flex items-center justify-center min-w-[180px] btn-pulse">
          <i class="fa fa-play mr-2"></i> 开始面试
        </button>

        <!-- 开始回答按钮 -->
        <button id="start-answer" class="bg-secondary hover:bg-secondary/90 text-white px-8 py-4 rounded-full font-medium transition-all shadow-lg hover:shadow-secondary/30 flex items-center justify-center min-w-[180px] opacity-50 cursor-not-allowed" disabled>
          <i class="fa fa-microphone mr-2"></i> 开始回答
        </button>

        <!-- 结束面试按钮 -->
        <button id="end-interview" class="bg-danger hover:bg-danger/90 text-white px-8 py-4 rounded-full font-medium transition-all shadow-lg hover:shadow-danger/30 flex items-center justify-center min-w-[180px] opacity-50 cursor-not-allowed" disabled>
          <i class="fa fa-stop mr-2"></i> 结束面试
        </button>
      </div>

      <!-- 行为分析说明 -->
      <div class="mt-8 bg-blue-50 border-l-4 border-primary p-4 rounded-r-lg max-w-2xl mx-auto text-sm text-gray-700 slide-up">
        <div class="flex">
          <div class="flex-shrink-0">
            <i class="fa fa-info-circle text-primary"></i>
          </div>
          <div class="ml-3">
            <p><strong>行为分析提示：</strong>系统将实时监测您的坐姿、表情和眼神交流情况。请保持良好的姿态，自然的表情，并适时与面试官进行眼神交流。</p>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- 笔试弹窗 -->
  <div id="exam-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden fade-in">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl mx-4 max-h-[90vh] flex flex-col">
      <div class="p-6 border-b border-gray-100">
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <div class="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center mr-3">
              <i class="fa fa-file-text-o text-primary"></i>
            </div>
            <div>
              <h2 class="text-xl font-bold">技术岗位笔试</h2>
              <p class="text-sm text-gray-500">共20题，限时30分钟</p>
            </div>
          </div>
          <div class="flex items-center">
            <div class="mr-4 text-right hidden sm:block">
              <div class="font-medium">剩余时间</div>
              <div id="exam-timer" class="text-xl font-mono">29:45</div>
            </div>
            <div class="w-12 h-12 bg-blue-50 rounded-full flex items-center justify-center">
              <span id="exam-progress-text" class="font-bold">0%</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 进度条 -->
      <div class="px-6 py-3 bg-gray-50">
        <div class="progress-bar">
          <div id="exam-progress-fill" class="progress-fill" style="width: 5%"></div>
        </div>
      </div>

      <!-- 笔试题目区域 -->
      <div class="exam-container p-6 flex-grow">
        <div id="exam-questions-container" class="space-y-6">
          <!-- 题目将通过JS动态生成 -->
        </div>
      </div>

      <div class="p-6 border-t border-gray-100 flex justify-between">
        <button id="exam-prev-btn" class="px-5 py-2.5 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
          <i class="fa fa-arrow-left mr-2"></i>上一题
        </button>
        <div class="flex items-center text-gray-500 text-sm">
          <span id="exam-current-question-number">1</span> / <span>20</span>
        </div>
        <button id="exam-next-btn" class="px-5 py-2.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
          下一题<i class="fa fa-arrow-right ml-2"></i>
        </button>
        <button id="exam-submit-btn" class="px-5 py-2.5 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-colors hidden">
          <i class="fa fa-paper-plane mr-2"></i>提交答卷
        </button>
      </div>
    </div>
  </div>

  <!-- 笔试结果弹窗 -->
  <div id="exam-result-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden fade-in p-4">
    <div class="bg-white rounded-2xl p-6 max-w-3xl w-full shadow-2xl">
      <div class="text-center mb-6">
        <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <i class="fa fa-check-circle text-3xl text-green-500"></i>
        </div>
        <h2 class="text-2xl font-bold">笔试已完成</h2>
        <p class="text-gray-500 mt-2">您的笔试成绩如下</p>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-blue-50 rounded-xl p-5 text-center">
          <div class="text-4xl font-bold text-primary mb-2" id="exam-score">85</div>
          <div class="text-gray-600">得分</div>
        </div>
        <div class="bg-green-50 rounded-xl p-5 text-center">
          <div class="text-4xl font-bold text-green-600 mb-2" id="exam-correct-count">17</div>
          <div class="text-gray-600">正确题数</div>
        </div>
        <div class="bg-orange-50 rounded-xl p-5 text-center">
          <div class="text-4xl font-bold text-orange-500 mb-2" id="exam-time-used">18:32</div>
          <div class="text-gray-600">用时</div>
        </div>
      </div>

      <div class="mb-6">
        <h3 class="font-bold text-lg mb-4 flex items-center">
          <i class="fa fa-bar-chart mr-2 text-primary"></i>答题分析
        </h3>
        <div id="exam-analysis-container" class="space-y-4">
          <!-- 分类正确率将通过JS动态生成 -->
        </div>
      </div>

      <div class="flex justify-center space-x-4">
        <button id="exam-review-btn" class="px-5 py-2.5 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
          <i class="fa fa-search mr-2"></i>查看答题详情
        </button>
        <button id="exam-continue-interview-btn" class="px-5 py-2.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
          <i class="fa fa-arrow-right mr-2"></i>继续面试
        </button>
      </div>
    </div>
  </div>

  <!-- 面试方向选择模态框 -->
  <div id="direction-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden fade-in">
    <div class="bg-white rounded-xl p-6 md:p-8 max-w-2xl w-full mx-4 shadow-2xl">
      <div class="text-center mb-6">
        <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
          <i class="fa fa-code-fork text-2xl text-primary"></i>
        </div>
        <h2 class="text-xl font-bold">选择面试方向</h2>
        <p class="text-gray-500 mt-2">请选择您想要模拟的技术面试方向</p>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        <!-- 数据库方向 -->
        <div class="direction-card border border-gray-200 rounded-lg p-4 cursor-pointer hover:border-primary hover:bg-primary/5">
          <div class="flex items-center">
            <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mr-4">
              <i class="fa fa-database text-xl text-primary"></i>
            </div>
            <div>
              <h3 class="font-semibold">数据库</h3>
              <p class="text-sm text-gray-500">SQL优化、数据建模等</p>
            </div>
          </div>
        </div>

        <!-- 深度学习方向 -->
        <div class="direction-card border border-gray-200 rounded-lg p-4 cursor-pointer hover:border-primary hover:bg-primary/5">
          <div class="flex items-center">
            <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mr-4">
              <i class="fa fa-brain text-xl text-primary"></i>
            </div>
            <div>
              <h3 class="font-semibold">深度学习</h3>
              <p class="text-sm text-gray-500">模型训练、算法原理等</p>
            </div>
          </div>
        </div>

        <!-- 前端方向 -->
        <div class="direction-card border border-gray-200 rounded-lg p-4 cursor-pointer hover:border-primary hover:bg-primary/5">
          <div class="flex items-center">
            <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mr-4">
              <i class="fa fa-html5 text-xl text-primary"></i>
            </div>
            <div>
              <h3 class="font-semibold">前端</h3>
              <p class="text-sm text-gray-500">框架应用、性能优化等</p>
            </div>
          </div>
        </div>

        <!-- 数通方向 -->
        <div class="direction-card border border-gray-200 rounded-lg p-4 cursor-pointer hover:border-primary hover:bg-primary/5">
          <div class="flex items-center">
            <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mr-4">
              <i class="fa fa-exchange text-xl text-primary"></i>
            </div>
            <div>
              <h3 class="font-semibold">数通</h3>
              <p class="text-sm text-gray-500">网络协议、路由交换等</p>
            </div>
          </div>
        </div>
      </div>

      <div class="flex space-x-3">
        <button id="cancel-direction" class="flex-1 bg-gray-100 text-gray-700 py-3 rounded-lg font-medium hover:bg-gray-200 transition-colors">
          取消
        </button>
        <button id="confirm-direction" class="flex-1 bg-primary text-white py-3 rounded-lg font-medium hover:bg-primary/90 transition-colors opacity-50 cursor-not-allowed" disabled>确认选择</button>
      </div>
    </div>
  </div>

  <!-- 简历上传模态框 -->
  <div id="resume-upload-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden fade-in">
    <div class="bg-white rounded-xl p-6 md:p-8 max-w-md w-full mx-4 shadow-2xl">
        <div class="text-center mb-6">
            <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fa fa-file-text-o text-2xl text-primary"></i>
            </div>
            <h2 class="text-xl font-bold">上传简历</h2>
            <p class="text-gray-500 mt-2">请上传您的简历图片，系统将进行分析</p>
            <p id="selected-direction" class="text-sm text-primary mt-1 hidden"></p>
        </div>
        <div class="mb-6">
            <label for="resume-upload" class="flex flex-col items-center justify-center w-full h-40 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition-colors">
                <div class="flex flex-col items-center justify-center pt-5 pb-6">
                    <i class="fa fa-cloud-upload text-3xl text-gray-400 mb-2"></i>
                    <p class="mb-2 text-sm text-gray-500"><span class="font-semibold">点击上传</span> 或拖放文件</p>
                    <p class="text-xs text-gray-400 mt-2">支持 JPG, PNG, PDF 格式 (最大 10MB)</p>
                </div>
                <input id="resume-upload" name="avatar" type="file" class="hidden" accept="image/jpeg, image/png, application/pdf" />
            </label>
            <div id="upload-progress" class="mt-4 hidden">
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="progress-bar" class="bg-primary h-2.5 rounded-full" style="width: 0%"></div>
                </div>
                <p id="upload-status" class="text-sm text-gray-500 mt-2 text-center">上传中...</p>
            </div>
        </div>
        <div class="flex space-x-3">
            <button id="cancel-upload" class="flex-1 bg-gray-100 text-gray-700 py-3 rounded-lg font-medium hover:bg-gray-200 transition-colors">
                取消
            </button>
            <button id="confirm-upload" class="flex-1 bg-primary text-white py-3 rounded-lg font-medium hover:bg-primary/90 transition-colors opacity-50 cursor-not-allowed" disabled>确认上传</button>
        </div>
    </div>
  </div>

  <!-- 面试结果模态框 -->
  <div id="interview-result-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden fade-in">
    <div class="bg-white rounded-xl p-6 md:p-8 max-w-md w-full mx-4 shadow-2xl">
      <div class="text-center mb-6">
        <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <i class="fa fa-check text-2xl text-green-500"></i>
        </div>
        <h2 class="text-xl font-bold">面试已结束</h2>
        <p class="text-gray-500 mt-2">感谢您完成本次模拟面试</p>
      </div>

      <div class="space-y-4 mb-6">
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">面试时长</span>
          <span class="font-medium" id="modal-duration">05:32</span>
        </div>
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">回答问题数</span>
          <span class="font-medium" id="modal-questions">2个</span>
        </div>
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">平均回答时长</span>
          <span class="font-medium" id="modal-average">1:45</span>
        </div>
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">面试方向</span>
          <span class="font-medium" id="modal-direction">数据库</span>
        </div>
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">行为评分</span>
          <span class="font-medium" id="behavior-score">85分</span>
        </div>
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">不良姿势次数</span>
          <span class="font-medium" id="bad-posture-count">0次</span>
        </div>
        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
          <span class="text-gray-600">眼神交流不足</span>
          <span class="font-medium" id="bad-eyecontact-count">0次</span>
        </div>
      </div>

      <div class="flex flex-col space-y-3">

        <button id="close-interview-modal" class="w-full bg-gray-100 text-gray-700 py-3 rounded-lg font-medium hover:bg-gray-200 transition-colors">
          关闭
        </button>
      </div>
    </div>
  </div>

  <!-- 音频元素 -->
  <audio id="opening-audio" preload="auto">
    <source src="{% static 'audio/opening.mp3' %}" type="audio/mpeg">
    您的浏览器不支持音频标签
  </audio>
  <audio id="question-audio-1" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-software-interface-start-2574.mp3" type="audio/mpeg">
  </audio>
  <audio id="question-audio-2" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-interface-hint-notification-911.mp3" type="audio/mpeg">
  </audio>
  <audio id="question-audio-3" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-correct-answer-tone-2870.mp3" type="audio/mpeg">
  </audio>
  <audio id="question-audio-4" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-achievement-bell-600.mp3" type="audio/mpeg">
  </audio>
  <audio id="question-audio-5" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-unlocking-563.mp3" type="audio/mpeg">
  </audio>
  <audio id="hint-audio" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-interface-hint-notification-911.mp3" type="audio/mpeg">
  </audio>
  <audio id="positive-feedback-audio" preload="auto">
    <source src="https://assets.mixkit.co/sfx/preview/mixkit-positive-interface-beep-221.mp3" type="audio/mpeg">
  </audio>

  <script>
// 全局配置与初始化
document.addEventListener('DOMContentLoaded', function() {
    initVoiceSelection();
    initEventListeners();
});

// ================== 全局变量 ==================
// 行为分析相关
let detector = null;
let detectionInterval = null;
let lastHintTime = 0;
let hintCooldown = 5000; // 提示冷却时间(ms)
let behaviorScores = {
    posture: 100,
    expression: 100,
    eyeContact: 100
};
let badBehaviorCount = {
    posture: 0,
    expression: 0,
    eyeContact: 0
};
let goodBehaviorCount = {
    posture: 0,
    expression: 0,
    eyeContact: 0
};
let lastScoreUpdateTime = 0;
let scoreUpdateInterval = 2000; // 评分更新间隔(ms)

// 状态变量
let isInterviewStarted = false;
let isAnswering = false;
let interviewStartTime = null;
let interviewTimerInterval = null;
let answerCount = 0;
let totalAnswerTime = 0;
let currentAnswerStartTime = null;
let speechSynthesisInProgress = false;
let lastGoodPostureTime = 0;
let lastGoodEyeContactTime = 0;

// 笔试相关
let examQuestions = [];
let userAnswers = [];
let examCurrentQuestionIndex = 0;
let examStartTime = null;
let examTimerInterval = null;

// 面试问题相关（核心修改）
let selectedDirection = '';
let randomQuestions = []; // 存储随机选择的3个问题
let currentQuestionIndex = 0;
let femaleVoice = null;

// 每个方向预设5个问题，从中随机选择3个
const questionPool = {
    "数据库": [
        "请解释ACID原则在数据库事务中的应用场景",
        "如何优化MySQL中百万级数据的查询性能？",
        "简述InnoDB与MyISAM存储引擎的主要区别",
        "什么是数据库索引？B+树索引与哈希索引有何不同？",
        "如何处理数据库死锁问题？请举例说明"
    ],
    "深度学习": [
        "请解释CNN卷积层的工作原理及应用场景",
        "Batch Normalization在神经网络中的作用是什么？",
        "如何解决深度学习模型的过拟合问题？",
        "简述RNN与LSTM的区别及适用场景",
        "目标检测算法中，YOLO与Faster R-CNN的主要区别是什么？"
    ],
    "前端": [
        "React的虚拟DOM与Diff算法原理是什么？",
        "如何优化前端项目的加载性能？请从多个维度说明",
        "Vue3的Composition API与Vue2的Options API相比有哪些优势？",
        "前端跨域问题的解决方案有哪些？各自适用场景是什么？",
        "浏览器的事件循环机制是如何工作的？"
    ],
    "数通": [
        "OSPF协议的工作原理及邻居建立过程是什么？",
        "TCP三次握手与四次挥手的详细过程及为什么需要这样设计？",
        "VLAN的作用是什么？如何实现跨交换机的VLAN通信？",
        "路由表的生成方式有哪些？动态路由协议的分类及特点？",
        "NAT技术的作用及常见类型有哪些？"
    ]
};

// DOM元素缓存
const elements = {
    // 面试核心元素
    startInterviewBtn: document.getElementById('start-interview'),
    startAnswerBtn: document.getElementById('start-answer'),
    endInterviewBtn: document.getElementById('end-interview'),
    userVideo: document.getElementById('user-video'),
    interviewerVideo: document.getElementById('interviewer-video'),
    interviewerListeningVideo: document.getElementById('interviewer-listening-video'),
    cameraPlaceholder: document.getElementById('camera-placeholder'),
    cameraLoading: document.getElementById('camera-loading'),
    interviewWaiting: document.getElementById('interview-waiting'),
    interviewerStatus: document.getElementById('interviewer-status'),
    interviewerListeningStatus: document.getElementById('interviewer-listening-status'),
    questionDisplay: document.getElementById('question-display'),
    recordingIndicator: document.getElementById('recording-indicator'),
    interviewResultModal: document.getElementById('interview-result-modal'),
    closeInterviewModalBtn: document.getElementById('close-interview-modal'),

    behaviorHints: document.getElementById('behavior-hints'),
    detectionCanvas: document.getElementById('detection-canvas'),
    behaviorScoreIndicator: document.getElementById('behavior-score-indicator'),
    currentScoreEl: document.getElementById('current-score'),
    scoreBar: document.getElementById('score-bar'),

    // 方向选择
    directionModal: document.getElementById('direction-modal'),
    cancelDirectionBtn: document.getElementById('cancel-direction'),
    confirmDirectionBtn: document.getElementById('confirm-direction'),
    directionCards: document.querySelectorAll('.direction-card'),
    selectedDirectionEl: document.getElementById('selected-direction'),
    modalDirectionEl: document.getElementById('modal-direction'),

    // 笔试相关
    examModal: document.getElementById('exam-modal'),
    examQuestionsContainer: document.getElementById('exam-questions-container'),
    examPrevBtn: document.getElementById('exam-prev-btn'),
    examNextBtn: document.getElementById('exam-next-btn'),
    examSubmitBtn: document.getElementById('exam-submit-btn'),
    examCurrentQuestionNumber: document.getElementById('exam-current-question-number'),
    examTimer: document.getElementById('exam-timer'),
    examProgressFill: document.getElementById('exam-progress-fill'),
    examProgressText: document.getElementById('exam-progress-text'),
    examResultModal: document.getElementById('exam-result-modal'),
    examReviewBtn: document.getElementById('exam-review-btn'),
    examContinueInterviewBtn: document.getElementById('exam-continue-interview-btn'),
    examAnalysisContainer: document.getElementById('exam-analysis-container'),

    // 音频
    openingAudio: document.getElementById('opening-audio'),
    questionAudios: [
        document.getElementById('question-audio-1'),
        document.getElementById('question-audio-2'),
        document.getElementById('question-audio-3'),
        document.getElementById('question-audio-4'),
        document.getElementById('question-audio-5')
    ],
    hintAudio: document.getElementById('hint-audio'),
    positiveFeedbackAudio: document.getElementById('positive-feedback-audio'),

    // 简历上传
    resumeUploadModal: document.getElementById('resume-upload-modal'),
    resumeUpload: document.getElementById('resume-upload'),
    confirmUpload: document.getElementById('confirm-upload'),
    cancelUpload: document.getElementById('cancel-upload'),
    uploadProgress: document.getElementById('upload-progress'),
    resumeProgressBar: document.getElementById('progress-bar'),
    uploadStatus: document.getElementById('upload-status')
};

// ================== 工具函数 ==================
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

const csrftoken = getCookie('csrftoken');
const canvasCtx = elements.detectionCanvas.getContext('2d');

// 从数组中随机选择指定数量的元素
function getRandomQuestions(arr, count) {
    const shuffled = [...arr].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, count);
}

// ================== 事件监听初始化 ==================
function initEventListeners() {
    // 面试控制
    elements.startInterviewBtn.addEventListener('click', () => {
        elements.directionModal.classList.remove('hidden');
    });

    elements.startAnswerBtn.addEventListener('click', toggleAnswer);
    elements.endInterviewBtn.addEventListener('click', endInterview);

    // 方向选择
    elements.cancelDirectionBtn.addEventListener('click', () => {
        elements.directionModal.classList.add('hidden');
        resetDirectionSelection();
    });

    elements.confirmDirectionBtn.addEventListener('click', confirmDirectionSelection);

    elements.directionCards.forEach(card => {
        card.addEventListener('click', () => {
            elements.directionCards.forEach(c => {
                c.classList.remove('border-primary', 'bg-primary/5');
                c.classList.add('border-gray-200');
            });
            card.classList.remove('border-gray-200');
            card.classList.add('border-primary', 'bg-primary/5');
            selectedDirection = card.querySelector('h3').textContent;
            elements.confirmDirectionBtn.disabled = false;
            elements.confirmDirectionBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        });
    });

    // 面试结果模态框
    elements.closeInterviewModalBtn.addEventListener('click', () => {
        elements.interviewResultModal.classList.add('hidden');
        resetInterview();
    });


    // 笔试控制
    document.getElementById('exam-link').addEventListener('click', (e) => {
        e.preventDefault();
        elements.examModal.classList.remove('hidden');
        initExam();
    });

    document.getElementById('mobile-exam-link').addEventListener('click', (e) => {
        e.preventDefault();
        document.getElementById('mobile-menu').classList.add('hidden');
        elements.examModal.classList.remove('hidden');
        initExam();
    });

    elements.examPrevBtn.addEventListener('click', () => {
        if (examCurrentQuestionIndex > 0) {
            examCurrentQuestionIndex--;
            renderExamQuestion(examCurrentQuestionIndex);
        }
    });

    elements.examNextBtn.addEventListener('click', () => {
        if (examCurrentQuestionIndex < examQuestions.length - 1) {
            examCurrentQuestionIndex++;
            renderExamQuestion(examCurrentQuestionIndex);
        }
    });

    elements.examSubmitBtn.addEventListener('click', submitExam);
    elements.examReviewBtn.addEventListener('click', reviewExam);
    elements.examContinueInterviewBtn.addEventListener('click', continueToInterview);

    // 简历上传
    elements.resumeUpload.addEventListener('change', handleResumeSelection);
    elements.cancelUpload.addEventListener('click', () => {
        elements.resumeUploadModal.classList.add('hidden');
        resetUploadState();
    });

    elements.confirmUpload.addEventListener('click', uploadResume);

    // 移动端菜单
    document.getElementById('menu-btn').addEventListener('click', () => {
        const mobileMenu = document.getElementById('mobile-menu');
        mobileMenu.classList.toggle('hidden');
    });

    // 滚动监听
    window.addEventListener('scroll', handleScroll);
}

// ================== 面试核心功能 ==================
async function startActualInterview() {
    if (isInterviewStarted) return;

    isInterviewStarted = true;
    elements.startInterviewBtn.disabled = true;
    elements.startInterviewBtn.classList.remove('btn-pulse');
    elements.startInterviewBtn.classList.add('opacity-50', 'cursor-not-allowed');

    elements.startAnswerBtn.disabled = true;
    elements.startAnswerBtn.classList.add('opacity-50', 'cursor-not-allowed');
    elements.endInterviewBtn.disabled = false;
    elements.endInterviewBtn.classList.remove('opacity-50', 'cursor-not-allowed');

    elements.cameraPlaceholder.classList.add('hidden');
    elements.cameraLoading.classList.remove('hidden');
    elements.interviewWaiting.classList.add('hidden');

    // 初始化行为分析器
    const detectorInitialized = await initDetector();

    interviewStartTime = new Date();
    interviewTimerInterval = setInterval(updateTimer, 1000);

    try {
        const stream = await navigator.mediaDevices.getUserMedia({
            video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' },
            audio: true
        });

        elements.userVideo.srcObject = stream;
        elements.userVideo.classList.remove('hidden');

        // 启动行为检测
        if (detectorInitialized) {
            startBehaviorDetection();
        }

        // 核心修改：从5个预设问题中随机选择3个
        randomQuestions = getRandomQuestions(questionPool[selectedDirection], 3);
        currentQuestionIndex = 0;

        setTimeout(() => {
            elements.cameraLoading.classList.add('hidden');
            elements.interviewerStatus.classList.remove('hidden');
            elements.questionDisplay.classList.remove('hidden');

            // 第一个问题：自我介绍（固定）
            const openingText = "你好面试者，欢迎来到我们公司，请您开始自我介绍一下可以包括您的工作经历、技能特长以及为何认为自己适合这个职位等方面的内容。请尽量详细一些，这样我们可以更好地了解您的背景和能力。";

            document.getElementById('current-question').textContent = openingText;
            elements.interviewerVideo.play();

            // 播放开场介绍
            speakText(openingText, () => {
                switchToListeningVideo();
                elements.startAnswerBtn.disabled = false;
                elements.startAnswerBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            });

        }, 1000);

    } catch (error) {
        console.error('获取摄像头失败:', error);
        elements.cameraLoading.classList.add('hidden');
        elements.cameraPlaceholder.innerHTML = `
          <i class="fa fa-exclamation-triangle text-5xl mb-4 text-red-500"></i>
          <p class="text-center px-8">无法访问摄像头</p>
          <p class="text-sm text-gray-400 mt-2">请确保已授予摄像头权限</p>
        `;
        resetInterview();
    }
}

function toggleAnswer() {
    if (!isInterviewStarted) return;

    if (speechSynthesisInProgress) {
        window.speechSynthesis.cancel();
        speechSynthesisInProgress = false;
    }

    if (!isAnswering) {
        // 开始回答
        isAnswering = true;
        elements.startAnswerBtn.innerHTML = '<i class="fa fa-stop mr-2"></i> 再次点击停止回答';
        elements.startAnswerBtn.classList.remove('bg-secondary', 'hover:bg-secondary/90');
        elements.startAnswerBtn.classList.add('bg-orange-500', 'hover:bg-orange-600');
        elements.recordingIndicator.classList.remove('hidden');

        switchToListeningVideo();
        elements.questionAudios.forEach(audio => audio.pause());
        currentAnswerStartTime = new Date();
    } else {
        // 停止回答
        isAnswering = false;
        elements.startAnswerBtn.innerHTML = '<i class="fa fa-microphone mr-2"></i> 开始回答';
        elements.startAnswerBtn.classList.remove('bg-orange-500', 'hover:bg-orange-600');
        elements.startAnswerBtn.classList.add('bg-secondary', 'hover:bg-secondary/90');
        elements.recordingIndicator.classList.add('hidden');

        answerCount++;
        const answerDuration = (new Date() - currentAnswerStartTime) / 1000;
        totalAnswerTime += answerDuration;

        currentQuestionIndex++;

        // 控制只提3个额外问题（加上开场问题共4个）
        if (currentQuestionIndex < randomQuestions.length) {
            elements.startAnswerBtn.disabled = true;
            elements.startAnswerBtn.classList.add('opacity-50', 'cursor-not-allowed');

            setTimeout(() => {
                playCurrentQuestion();
            }, 500);
        } else {
            // 所有问题结束
            document.getElementById('current-question').textContent = "您已完成所有问题，是否结束面试？";
            elements.startAnswerBtn.disabled = true;
            elements.startAnswerBtn.classList.add('opacity-50', 'cursor-not-allowed');
        }
    }
}

// 保存面试数据的函数
function saveInterviewData(data) {
    console.log('待发送数据:', data);// 检查控制台是否有数据
    // 使用Fetch API发送POST请求
    fetch('/save/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken  // 使用之前定义的CSRF令牌
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(result => {
        console.log('数据保存成功:', result);
        // 可以在这里添加保存成功的提示或其他逻辑
    })
    .catch(error => {
        console.error('保存数据时出错:', error);
        // 可以在这里添加保存失败的提示或重试逻辑
    });
}
function endInterview() {
    if (!isInterviewStarted) return;

    window.speechSynthesis.cancel();

    // 停止行为检测
    if (detectionInterval) {
        clearInterval(detectionInterval);
    }

    // 计算最终评分
    calculateFinalScore();
    const finalScore = calculateFinalScore();
    clearInterval(interviewTimerInterval);

    const averageAnswerTime = answerCount > 0 ? Math.floor(totalAnswerTime / answerCount) : 0;
    document.getElementById('modal-questions').textContent = `${answerCount}个`;
    document.getElementById('modal-average').textContent = formatTime(averageAnswerTime);

      // 准备要提交的数据
    const interviewData = {
        // 笔试得分 - 从笔试结果中获取
        exam_score: document.getElementById('exam-score') ? parseInt(document.getElementById('exam-score').textContent) : 0,
        // 面试总分
        interview_score: finalScore,
        // 坐姿表现分
        posture_score: behaviorScores.posture,
        // 表情表现分
        expression_score: behaviorScores.expression,
        // 眼神交流分
        eye_contact_score: behaviorScores.eyeContact,
        //面试方向
        fx: selectedDirection
        // 其他可选数据
        {#interview_duration: document.getElementById('modal-duration').textContent,#}
        {#question_count: answerCount,#}
        {#average_answer_time: formatTime(averageAnswerTime),#}
        {#interview_direction: selectedDirection#}
    };
      // 发送AJAX请求保存数据
        saveInterviewData(interviewData);
    elements.interviewResultModal.classList.remove('hidden');

    if (elements.userVideo.srcObject) {
        elements.userVideo.srcObject.getTracks().forEach(track => track.stop());
    }
    elements.interviewerVideo.pause();
    elements.interviewerListeningVideo.pause();
    elements.questionAudios.forEach(audio => audio.pause());

}

function resetInterview() {
    window.speechSynthesis.cancel();

    // 停止行为检测
    if (detectionInterval) {
        clearInterval(detectionInterval);
        detectionInterval = null;
    }

    // 清空画布
    if (canvasCtx) {
        canvasCtx.clearRect(0, 0, elements.detectionCanvas.width, elements.detectionCanvas.height);
    }

    // 清空提示
    elements.behaviorHints.innerHTML = '';

    // 重置评分
    behaviorScores = {
        posture: 100,
        expression: 100,
        eyeContact: 100
    };
    badBehaviorCount = {
        posture: 0,
        expression: 0,
        eyeContact: 0
    };
    goodBehaviorCount = {
        posture: 0,
        expression: 0,
        eyeContact: 0
    };

    // 重置状态
    isInterviewStarted = false;
    isAnswering = false;
    interviewStartTime = null;
    answerCount = 0;
    totalAnswerTime = 0;
    selectedDirection = '';
    randomQuestions = [];
    currentQuestionIndex = 0;
    speechSynthesisInProgress = false;
    lastGoodPostureTime = 0;
    lastGoodEyeContactTime = 0;

    // 重置UI
    elements.userVideo.classList.add('hidden');
    elements.userVideo.srcObject = null;
    elements.cameraPlaceholder.classList.remove('hidden');
    elements.interviewWaiting.classList.remove('hidden');
    elements.interviewerStatus.classList.add('hidden');
    elements.interviewerListeningStatus.classList.add('hidden');
    elements.questionDisplay.classList.add('hidden');
    elements.recordingIndicator.classList.add('hidden');
    elements.detectionCanvas.classList.add('hidden');
    elements.behaviorScoreIndicator.classList.add('hidden');

    // 重置视频
    elements.interviewerVideo.pause();
    elements.interviewerListeningVideo.pause();
    elements.questionAudios.forEach(audio => audio.pause());

    document.getElementById('current-question').textContent = "请介绍一下您的项目经验，以及您在项目中担任的角色和贡献？";

    // 重置按钮
    elements.startInterviewBtn.disabled = false;
    elements.startInterviewBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    elements.startInterviewBtn.classList.add('btn-pulse');

    elements.startAnswerBtn.disabled = true;
    elements.startAnswerBtn.classList.add('opacity-50', 'cursor-not-allowed');
    elements.startAnswerBtn.innerHTML = '<i class="fa fa-microphone mr-2"></i> 开始回答';
    elements.startAnswerBtn.classList.remove('bg-orange-500', 'hover:bg-orange-600');
    elements.startAnswerBtn.classList.add('bg-secondary', 'hover:bg-secondary/90');

    elements.endInterviewBtn.disabled = true;
    elements.endInterviewBtn.classList.add('opacity-50', 'cursor-not-allowed');

    resetDirectionSelection();
}

// ================== 行为分析功能引入 ==================
// 重试机制函数（确保先定义）
async function retry(fn, retriesLeft = 3, interval = 1000) {
    try {
        return await fn();
    } catch (error) {
        if (retriesLeft <= 0) {
            console.log('重试次数已用完');
            throw error;
        }
        console.log(`重试中... 剩余尝试次数: ${retriesLeft}`);
        await new Promise(resolve => setTimeout(resolve, interval));
        return retry(fn, retriesLeft - 1, interval);
    }
}

// 初始化检测器的主函数
async function initDetector() {
    try {
        // 检查TensorFlow.js和pose-detection是否加载
        if (typeof tf === 'undefined' || typeof poseDetection === 'undefined') {
            console.error('TensorFlow.js或pose-detection库未加载');
            showBehaviorHint('行为分析系统初始化失败：依赖库未加载', 'center');
            return false;
        }

        // 等待TensorFlow.js准备就绪
        await tf.ready();
        console.log('TensorFlow.js已准备好');

        // 检查MoveNet模型是否可用
        if (!poseDetection.SupportedModels.MoveNet) {
            console.error('MoveNet模型不可用');
            showBehaviorHint('行为分析系统初始化失败：MoveNet模型不可用', 'center');
            return false;
        }

        // 创建检测器（关键：不手动指定modelUrl，让库自动处理）
        const model = poseDetection.SupportedModels.MoveNet;
        const detectorConfig = {
            modelType: poseDetection.movenet.modelType.SINGLEPOSE_LIGHTNING,
            // 移除手动modelUrl，使用库默认路径
            enableSmoothing: true, // 可选：启用姿势平滑
            scoreThreshold: 0.5    // 可选：关键点置信度阈值
        };

        // 记录模型加载开始时间
        const startTime = performance.now();
        console.log('开始加载MoveNet模型（使用库默认路径）...');

        // 使用重试机制加载模型
        detector = await retry(() => poseDetection.createDetector(model, detectorConfig), 3);

        // 记录模型加载完成时间
        const loadTime = Math.round(performance.now() - startTime);
        console.log(`MoveNet模型加载成功，耗时 ${loadTime}ms`);

        // 显示成功提示
        showBehaviorHint('行为分析系统初始化成功', 'center', true);
        return true;
    } catch (error) {
        console.error('姿势检测器初始化失败:', error);

        // 提供更详细的错误信息
        if (error.message.includes('404')) {
            showBehaviorHint('模型文件未找到，可能是库版本不兼容，请尝试更新依赖', 'center');
        } else if (error.message.includes('CORS')) {
            showBehaviorHint('跨域错误，建议使用Chrome浏览器或部署到服务器', 'center');
        } else if (error.message.includes('WebGL')) {
            showBehaviorHint('浏览器不支持WebGL，请切换到Chrome/Firefox', 'center');
        } else {
            showBehaviorHint(`初始化失败: ${error.message}`, 'center');
        }

        return false;
    }
}

// 尝试多个CDN源获取可用的模型URL
async function getWorkingModelUrl() {
    const modelUrls = [
        // 官方CDN (最新版本)
        'https://cdn.jsdelivr.net/npm/@tensorflow-models/pose-detection@2.10.0/dist/movenet/singlepose-lightning/model.json',
        // UNPKG CDN
        'https://unpkg.com/@tensorflow-models/pose-detection@2.10.0/dist/movenet/singlepose-lightning/model.json',
        // 国内镜像 (如果有的话)
        'https://cdn.tailwindcss.com/@tensorflow-models/pose-detection@2.10.0/dist/movenet/singlepose-lightning/model.json'
    ];

    // 测试每个URL是否可用
    for (const url of modelUrls) {
        try {
            console.log(`尝试模型URL: ${url}`);
            const response = await fetch(url, { method: 'HEAD' });
            if (response.ok) {
                console.log(`找到可用模型URL: ${url}`);
                return url;
            }
        } catch (error) {
            console.warn(`URL ${url} 测试失败: ${error.message}`);
        }
    }

    // 如果没有找到可用的URL，返回默认值并抛出警告
    const defaultUrl = modelUrls[0];
    console.warn(`没有找到可用的模型URL，使用默认URL: ${defaultUrl}`);
    return defaultUrl;
}

function startBehaviorDetection() {
    if (!detector || !elements.userVideo.srcObject) return;

    // 设置canvas尺寸
    elements.detectionCanvas.width = elements.userVideo.videoWidth;
    elements.detectionCanvas.height = elements.userVideo.videoHeight;
    elements.detectionCanvas.classList.remove('hidden');

    // 显示评分指示器
    elements.behaviorScoreIndicator.classList.remove('hidden');
    updateScoreDisplay();

    // 定期检测
    detectionInterval = setInterval(async () => {
        if (!isInterviewStarted || !detector) return;

        try {
            const poses = await detector.estimatePoses(elements.userVideo);

            if (poses.length > 0) {
                const pose = poses[0];
                drawPose(pose);
                analyzePose(pose);
            } else {
                // 未检测到人体
                if (Date.now() - lastHintTime > hintCooldown) {
                    showBehaviorHint('未检测到您的位置，请调整坐姿', 'center');
                    updateBehaviorScore('posture', -5);
                    badBehaviorCount.posture++;
                    lastHintTime = Date.now();
                }
            }
        } catch (error) {
            console.error('姿势检测出错:', error);
        }
    }, 1000);
}
// ================== 行为分析功能 ==================
// 重试机制函数（确保先定义）
// 全局变量（情绪相关增强）
let emotionScores = {
    happy: 0,
    sad: 0,
    angry: 0,
    surprised: 0,
    neutral: 1
};
let currentEmotion = 'neutral';
let emotionCooldown = 1000; // 缩短冷却时间，提高响应速度
let lastEmotionUpdate = 0;
let emotionHistory = [];
let lastEmotion = ''; // 用于检测情绪变化

// 绘制函数保持不变，确保情绪显示
function drawPose(pose) {
    // 原有绘制逻辑...
    if (!pose || !pose.keypoints) return;

    // 清空画布
    canvasCtx.clearRect(0, 0, elements.detectionCanvas.width, elements.detectionCanvas.height);

    // 绘制关键点（增加对undefined的判断）
    pose.keypoints.forEach(keypoint => {
        // 关键修复：跳过undefined的关键点
        if (!keypoint) return;

        if (keypoint.score > 0.5) {
            canvasCtx.beginPath();
            canvasCtx.arc(keypoint.x, keypoint.y, 5, 0, 2 * Math.PI);

            // 根据评分改变颜色
            if (behaviorScores.posture < 70 || behaviorScores.eyeContact < 70) {
                canvasCtx.fillStyle = '#FF5757';
            } else if (behaviorScores.posture > 90 && behaviorScores.eyeContact > 90) {
                canvasCtx.fillStyle = '#36D399';
            } else {
                canvasCtx.fillStyle = '#165DFF';
            }

            canvasCtx.fill();
        }
    });

    // 绘制连接线（增加对无效关键点的判断）
    const connections = [
        [0, 1], [1, 2], [2, 3], [3, 4], // 面部
        [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], // 左臂
        [11, 12], [12, 13], [13, 14], [14, 15], [15, 16], // 右臂
        [11, 5], [12, 6], // 肩到脸
        [11, 12], // 肩膀
        [11, 23], [12, 24], // 肩到腰
        [23, 24], [23, 25], [24, 26], [25, 27], [26, 28] // 身体和腿
    ];

    connections.forEach(connection => {
        const [startIdx, endIdx] = connection;
        const startKp = pose.keypoints[startIdx];
        const endKp = pose.keypoints[endIdx];

        // 关键修复：确保两个关键点都存在且有score属性
        if (!startKp || !endKp || !startKp.score || !endKp.score) return;

        if (startKp.score > 0.5 && endKp.score > 0.5) {
            canvasCtx.beginPath();
            canvasCtx.moveTo(startKp.x, startKp.y);
            canvasCtx.lineTo(endKp.x, endKp.y);

            // 根据评分改变颜色
            if (behaviorScores.posture < 70 || behaviorScores.eyeContact < 70) {
                canvasCtx.strokeStyle = '#FF5757';
            } else if (behaviorScores.posture > 90 && behaviorScores.eyeContact > 90) {
                canvasCtx.strokeStyle = '#36D399';
            } else {
                canvasCtx.strokeStyle = '#165DFF';
            }

            canvasCtx.lineWidth = 2;
            canvasCtx.stroke();
        }
    });
    // 绘制当前情绪及评分占比
    if (currentEmotion) {
        canvasCtx.fillStyle = '#ffffff';
        canvasCtx.font = '16px Arial';
        canvasCtx.fillText(`情绪: ${currentEmotion} (评分占比20%)`, 10, 30);
    }
}
// 姿势分析函数 - 已集成情绪分析（内联情绪分析和提示逻辑）
function analyzePose(pose) {
    if (!pose || !pose.keypoints) return;

    // 获取关键节点（增加对undefined的容错）
    const nose = pose.keypoints.find(kp => kp && kp.name === 'nose');
    const leftShoulder = pose.keypoints.find(kp => kp && kp.name === 'left_shoulder');
    const rightShoulder = pose.keypoints.find(kp => kp && kp.name === 'right_shoulder');
    const leftHip = pose.keypoints.find(kp => kp && kp.name === 'left_hip');
    const rightHip = pose.keypoints.find(kp => kp && kp.name === 'right_hip');
    const leftEye = pose.keypoints.find(kp => kp && kp.name === 'left_eye');
    const rightEye = pose.keypoints.find(kp => kp && kp.name === 'right_eye');

    // 检查关键点
    if (!nose || !leftShoulder || !rightShoulder || !leftHip || !rightHip) {
        if (Date.now() - lastHintTime > hintCooldown) {
            showBehaviorHint('请坐直，确保全身可见', 'center');
            updateBehaviorScore('posture', -5);
            badBehaviorCount.posture++;
            lastHintTime = Date.now();
        }
        return;
    }

    // 坐姿检测
    const shoulderDistance = Math.abs(leftShoulder.x - rightShoulder.x);
    const shoulderToHipY = (leftHip.y + rightHip.y) / 2 - (leftShoulder.y + rightShoulder.y) / 2;

    // 肩膀倾斜检测
    const shoulderTilt = Math.abs(leftShoulder.y - rightShoulder.y);
    if (shoulderTilt > shoulderDistance * 0.3) {
        if (Date.now() - lastHintTime > hintCooldown) {
            showBehaviorHint('请注意坐姿，肩膀不要倾斜', 'top');
            updateBehaviorScore('posture', -3);
            badBehaviorCount.posture++;
            lastHintTime = Date.now();
        }
    } else if (shoulderTilt < shoulderDistance * 0.1 &&
              Date.now() - lastGoodPostureTime > 10000) {
        showBehaviorHint('坐姿良好，继续保持！', 'top', true);
        updateBehaviorScore('posture', 2);
        goodBehaviorCount.posture++;
        lastGoodPostureTime = Date.now();
    }

    // 身体前倾/后仰检测
    if (shoulderToHipY < shoulderDistance * 0.8) {
        if (Date.now() - lastHintTime > hintCooldown) {
            showBehaviorHint('请坐直，保持良好姿态', 'top');
            updateBehaviorScore('posture', -3);
            badBehaviorCount.posture++;
            lastHintTime = Date.now();
        }
    } else if (shoulderToHipY > shoulderDistance * 1.2 &&
              Date.now() - lastGoodPostureTime > 10000) {
        showBehaviorHint('坐姿端正，非常好！', 'top', true);
        updateBehaviorScore('posture', 2);
        goodBehaviorCount.posture++;
        lastGoodPostureTime = Date.now();
    }

    // 眼神交流检测
    const videoWidth = elements.userVideo.videoWidth;
    const centerX = videoWidth / 2;
    const noseOffset = Math.abs(nose.x - centerX);

    if (noseOffset > videoWidth * 0.3) {
        if (Date.now() - lastHintTime > hintCooldown) {
            showBehaviorHint('请面向摄像头，保持眼神交流', 'left');
            updateBehaviorScore('eyeContact', -4);
            badBehaviorCount.eyeContact++;
            lastHintTime = Date.now();
        }
    } else if (noseOffset < videoWidth * 0.1 &&
              Date.now() - lastGoodEyeContactTime > 10000) {
        showBehaviorHint('眼神交流良好，继续保持！', 'right', true);
        updateBehaviorScore('eyeContact', 3);
        goodBehaviorCount.eyeContact++;
        lastGoodEyeContactTime = Date.now();
    }

    // 表情分析
    if (leftEye && rightEye) {
        const eyeDistance = Math.abs(leftEye.x - rightEye.x);
        const headTilt = Math.abs((leftEye.y + rightEye.y)/2 - (leftShoulder.y + rightShoulder.y)/2);

        if (headTilt > eyeDistance * 1.5) {
            if (Date.now() - lastHintTime > hintCooldown) {
                showBehaviorHint('请保持自然表情，头部不要过度倾斜', 'top');
                updateBehaviorScore('expression', -3);
                badBehaviorCount.expression++;
                lastHintTime = Date.now();
            }
        } else if (headTilt < eyeDistance * 0.8) {
            updateBehaviorScore('expression', 1);
            goodBehaviorCount.expression++;
        }
    }

    // 情绪分析（内联逻辑，不通过函数调用）
    if (Date.now() - lastEmotionUpdate < emotionCooldown) return;

    // 重置情绪分数
    emotionScores = { happy: 0, sad: 0, angry: 0, surprised: 0, neutral: 1 };

    // 获取关键面部点

    const leftEyebrow = pose.keypoints.find(kp => kp && kp.name === 'left_eyebrow');
    const rightEyebrow = pose.keypoints.find(kp => kp && kp.name === 'right_eyebrow');
    const mouthLeft = pose.keypoints.find(kp => kp && kp.name === 'mouth_left');
    const mouthRight = pose.keypoints.find(kp => kp && kp.name === 'mouth_right');
    const mouthCenter = pose.keypoints.find(kp => kp && kp.name === 'mouth_center');

    // 关键面部点缺失处理
    if (!leftEye || !rightEye || !leftEyebrow || !rightEyebrow || !mouthLeft || !mouthRight || !mouthCenter) {
        currentEmotion = 'neutral';
        return;
    }

    // 面部特征计算
    const eyeDistance = Math.abs(leftEye.x - rightEye.x);
    const eyebrowEyeDistance = (Math.abs(leftEyebrow.y - leftEye.y) + Math.abs(rightEyebrow.y - rightEye.y)) / 2;
    const mouthWidth = Math.abs(mouthLeft.x - mouthRight.x);
    const mouthOpenness = Math.abs(mouthCenter.y - ((mouthLeft.y + mouthRight.y) / 2));

    // 情绪判定增强（增加权重值，提高识别灵敏度）
    // 1. 快乐（微笑）
    if (mouthOpenness > eyeDistance * 0.2 && mouthWidth > eyeDistance * 1.2) {
        emotionScores.happy += 2; // 提高权重
    }

    // 2. 悲伤
    if (eyebrowEyeDistance < eyeDistance * 0.3 && mouthCenter.y > ((mouthLeft.y + mouthRight.y) / 2 + eyeDistance * 0.1)) {
        emotionScores.sad += 2;
    }

    // 3. 愤怒
    if (eyebrowEyeDistance > eyeDistance * 0.5 && Math.abs(leftEyebrow.x - rightEyebrow.x) < eyeDistance * 0.8 && mouthOpenness < eyeDistance * 0.1) {
        emotionScores.angry += 2;
    }

    // 4. 惊讶
    if (eyebrowEyeDistance > eyeDistance * 0.6 && mouthOpenness > eyeDistance * 0.3 && Math.abs(mouthWidth - mouthOpenness) < eyeDistance * 0.2) {
        emotionScores.surprised += 2;
    }

    // 确定主导情绪
    let dominantEmotion = 'neutral';
    let maxScore = 0;
    for (const [emotion, score] of Object.entries(emotionScores)) {
        if (score > maxScore) {
            maxScore = score;
            dominantEmotion = emotion;
        }
    }

    // 情绪历史平滑
    emotionHistory.push(dominantEmotion);
    if (emotionHistory.length > 3) emotionHistory.shift();

    // 多数表决确定最终情绪
    const emotionCounts = emotionHistory.reduce((acc, emotion) => {
        acc[emotion] = (acc[emotion] || 0) + 1;
        return acc;
    }, {});

    let mostFrequentEmotion = 'neutral';
    let highestCount = 0;
    for (const [emotion, count] of Object.entries(emotionCounts)) {
        if (count > highestCount) {
            highestCount = count;
            mostFrequentEmotion = emotion;
        }
    }

    // 情绪变化时立即触发提醒
    if (mostFrequentEmotion !== currentEmotion) {
        lastEmotion = currentEmotion;
        currentEmotion = mostFrequentEmotion;
        lastEmotionUpdate = Date.now();

        // 情绪变化时强制更新评分
        updateScoreDisplay();

        // 触发情绪提醒（内联原triggerEmotionHint函数逻辑）
        const emotionHints = {
            happy: {
                message: '保持积极的情绪状态，非常好！',
                isPositive: true,
                position: 'right'
            },
            sad: {
                message: '尝试展现更积极的情绪，会给面试官更好的印象',
                isPositive: false,
                position: 'left'
            },
            angry: {
                message: '请注意控制情绪，保持平和的态度',
                isPositive: false,
                position: 'left'
            },
            surprised: {
                message: '保持自然的情绪表达会更合适',
                isPositive: false,
                position: 'top'
            },
            neutral: {
                message: '可以适当展现更积极的情绪，增加亲和力',
                isPositive: false,
                position: 'top'
            }
        };

        const hint = emotionHints[currentEmotion];
        if (hint) {
            showBehaviorHint(hint.message, hint.position, hint.isPositive);
        }
         updateScoreDisplay()
    }

    // 基于情绪的评分更新
    updateBehaviorScoreBasedOnEmotion(currentEmotion);
}
// 基于情绪的评分更新（增强版）
function updateBehaviorScoreBasedOnEmotion(emotion) {
    // 情绪对基础分的影响（直接加分/减分）
    const scoreChanges = {
        happy: 5,
        sad: -3,
        angry: -5,
        surprised: -2,
        neutral: 0
    };

    // 直接作用于表情分
    updateBehaviorScore('expression', scoreChanges[emotion]);
}
// 情绪单独计分函数
function getEmotionScore() {
    const emotionScores = {
        happy: 90,
        neutral: 70,
        surprised: 60,
        sad: 50,
        angry: 40
    };
    return emotionScores[currentEmotion] || 70;
}

function showBehaviorHint(message, position = 'top', isPositive = false) {
    // 播放提示音
    if (isPositive) {
        elements.positiveFeedbackAudio.currentTime = 0;
        elements.positiveFeedbackAudio.play().catch(e => console.log('正面反馈音播放失败:', e));
    } else {
        elements.hintAudio.currentTime = 0;
        elements.hintAudio.play().catch(e => console.log('提示音播放失败:', e));
    }

    // 创建提示元素
    const hintEl = document.createElement('div');
    hintEl.className = `absolute ${getPositionClass(position)} ${isPositive ? 'bg-secondary' : 'bg-warning'} text-white px-3 py-2 rounded-lg text-sm font-medium z-10 behavior-hint flex items-center`;
    hintEl.innerHTML = `<i class="fa ${isPositive ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-2"></i>${message}`;

    // 添加到容器
    elements.behaviorHints.appendChild(hintEl);

    // 自动移除
    setTimeout(() => {
        hintEl.remove();
    }, 4000);
}

function getPositionClass(position) {
    switch(position) {
        case 'top': return 'top-4 left-1/2 transform -translate-x-1/2';
        case 'bottom': return 'bottom-4 left-1/2 transform -translate-x-1/2';
        case 'left': return 'top-1/2 left-4 transform -translate-y-1/2';
        case 'right': return 'top-1/2 right-4 transform -translate-y-1/2';
        case 'center': return 'top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2';
        default: return 'top-4 left-4';
    }
}

function updateBehaviorScore(type, change) {
    behaviorScores[type] = Math.max(0, Math.min(100, behaviorScores[type] + change));

    // 更新显示
    if (Date.now() - lastScoreUpdateTime > scoreUpdateInterval) {
        updateScoreDisplay();
        lastScoreUpdateTime = Date.now();
    }
}

function updateScoreDisplay() {
    const finalScore = calculateFinalScore();
    elements.currentScoreEl.textContent = finalScore;
    elements.scoreBar.style.width = `${finalScore}%`;
    const emotionScore = getEmotionScore();
    document.getElementById('emotion-score').textContent = `${emotionScore}分`;

    // 颜色变化
    if (finalScore < 60) {
        elements.scoreBar.classList.remove('bg-primary', 'bg-secondary');
        elements.scoreBar.classList.add('bg-danger');
        elements.currentScoreEl.classList.add('text-danger');
        elements.currentScoreEl.classList.remove('text-primary', 'text-secondary');
    } else if (finalScore < 80) {
        elements.scoreBar.classList.remove('bg-danger', 'bg-secondary');
        elements.scoreBar.classList.add('bg-primary');
        elements.currentScoreEl.classList.add('text-primary');
        elements.currentScoreEl.classList.remove('bg-danger', 'text-secondary');
    } else {
        elements.scoreBar.classList.remove('bg-danger', 'bg-primary');
        elements.scoreBar.classList.add('bg-secondary');
        elements.currentScoreEl.classList.add('text-secondary');
        elements.currentScoreEl.classList.remove('bg-danger', 'text-primary');
    }

    // 低分时闪烁
    if (finalScore < 60 && !elements.scoreBar.classList.contains('blink')) {
        elements.scoreBar.classList.add('blink');
    } else if (finalScore >= 60 && elements.scoreBar.classList.contains('blink')) {
        elements.scoreBar.classList.remove('blink');
    }
}

function calculateFinalScore() {
    // 姿势60%，表情20%，眼神20%
    const finalScore = Math.round(
        behaviorScores.posture * 0.6 +
        behaviorScores.expression * 0.2 +
        behaviorScores.eyeContact * 0.2
    );
    document.getElementById('behavior-score').textContent = `${finalScore}分`;
    document.getElementById('bad-posture-count').textContent = `${badBehaviorCount.posture}次`;
    document.getElementById('bad-eyecontact-count').textContent = `${badBehaviorCount.eyeContact}次`;
    return finalScore;
}

// ================== 语音合成功能 ==================
function initVoiceSelection() {
    if ('speechSynthesis' in window) {
        window.speechSynthesis.onvoiceschanged = function() {
            const voices = window.speechSynthesis.getVoices();
            femaleVoice = voices.find(voice =>
                (voice.name.includes('Chinese') || voice.lang.includes('zh')) &&
                (voice.name.includes('Female') || voice.name.includes('女') || voice.gender === 'female')
            );

            if (!femaleVoice) {
                femaleVoice = voices.find(voice =>
                    (voice.name.includes('Chinese') || voice.lang.includes('zh')) ||
                    voice.default
                );
            }
        };
        window.speechSynthesis.getVoices();
    }
}

function speakText(text, onEnd) {
    if (!('speechSynthesis' in window)) {
        if (onEnd && typeof onEnd === 'function') {
            setTimeout(onEnd, 2000);
        }
        return null;
    }

    window.speechSynthesis.cancel();

    const speech = new SpeechSynthesisUtterance();
    speech.text = text;
    speech.lang = "zh-CN";
    speech.rate = 0.9;
    speech.pitch = 1.1;
    speech.volume = 1;

    if (femaleVoice) {
        speech.voice = femaleVoice;
    }

    if (onEnd && typeof onEnd === 'function') {
        speech.onend = onEnd;
    }

    window.speechSynthesis.speak(speech);
    return speech;
}

// ================== 笔试功能 ==================
function initExam() {
    examQuestions = [];
    userAnswers = [];
    examCurrentQuestionIndex = 0;

    // 从后端获取题目
    fetchExamQuestions();
}

function fetchExamQuestions() {
    // 显示加载状态
    elements.examQuestionsContainer.innerHTML = `
        <div class="flex justify-center items-center h-60">
            <div class="text-center">
                <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                <p>正在加载题目...</p>
            </div>
        </div>
    `;

    // 从后端获取题目
    fetch('/get_q/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: JSON.stringify({ direction: selectedDirection || '前端' })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('获取题目失败');
        }
        return response.json();
    })
    .then(data => {
        if (data.questions && data.questions.length > 0) {
            // 处理题目数据
            examQuestions = data.questions.map((q, index) => ({
                id: index + 1,
                question: q.question_text,
                options: [q.A, q.B, q.C, q.D],
                answer: q.answer,
                explanation: q.jx,
                category: selectedDirection || '前端'
            }));

            // 初始化答案数组
            userAnswers = Array(examQuestions.length).fill(null);

            // 渲染第一题
            renderExamQuestion(0);
            startExamTimer();
            updateExamProgress();
        } else {
            throw new Error('未获取到有效题目');
        }
    })
    .catch(error => {
        console.error('获取题目出错:', error);
        elements.examQuestionsContainer.innerHTML = `
            <div class="flex justify-center items-center h-60 text-center">
                <div>
                    <i class="fa fa-exclamation-triangle text-3xl text-red-500 mb-4"></i>
                    <p class="text-red-500">获取题目失败: ${error.message}</p>
                    <button id="retry-load-questions" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg">
                        重试
                    </button>
                </div>
            </div>
        `;

        // 重试按钮
        document.getElementById('retry-load-questions').addEventListener('click', fetchExamQuestions);
    });
}

function renderExamQuestion(index) {
    const question = examQuestions[index];
    elements.examCurrentQuestionNumber.textContent = index + 1;

    // 生成选项HTML
    const optionsHtml = question.options.map((option, i) => {
        const optionLetter = String.fromCharCode(97 + i); // a, b, c, d
        const isSelected = userAnswers[index] === optionLetter;
        const formattedOption = `${optionLetter}) ${option}`;

        return `
            <div class="option-item p-4 rounded-lg border border-gray-200 mb-3 cursor-pointer ${isSelected ? 'selected' : ''}"
                 data-option="${optionLetter}">
                ${formattedOption}
            </div>
        `;
    }).join('');

    // 渲染题目
    elements.examQuestionsContainer.innerHTML = `
        <div class="question-card bg-white rounded-xl p-6 shadow-sm">
            <div class="flex items-start mb-5">
                <div class="w-8 h-8 bg-primary/10 text-primary rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                    ${index + 1}
                </div>
                <div class="font-medium text-lg">${question.question}</div>
            </div>
            <div class="options-container ml-11">
                ${optionsHtml}
            </div>
        </div>
    `;

    // 选项点击事件
    document.querySelectorAll('.option-item').forEach(item => {
        item.addEventListener('click', () => {
            const selectedOption = item.dataset.option;
            userAnswers[index] = selectedOption;
            renderExamQuestion(index);
            updateExamProgress();
        });
    });

    // 更新按钮状态
    elements.examPrevBtn.disabled = index === 0;
    elements.examPrevBtn.classList.toggle('opacity-50', index === 0);
    elements.examNextBtn.classList.toggle('hidden', index === examQuestions.length - 1);
    elements.examSubmitBtn.classList.toggle('hidden', index !== examQuestions.length - 1);
}

function updateExamProgress() {
    const answeredCount = userAnswers.filter(answer => answer !== null).length;
    const progress = Math.round((answeredCount / examQuestions.length) * 100);
    elements.examProgressText.textContent = `${progress}%`;
    elements.examProgressFill.style.width = `${progress}%`;
}

function startExamTimer() {
    if (examTimerInterval) {
        clearInterval(examTimerInterval);
    }

    const examDuration = 30 * 60; // 30分钟
    let timeLeft = examDuration;
    examStartTime = new Date();

    examTimerInterval = setInterval(() => {
        timeLeft--;

        if (timeLeft <= 0) {
            clearInterval(examTimerInterval);
            submitExam();
            return;
        }

        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        elements.examTimer.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        // 时间不足提醒
        if (timeLeft < 300 && timeLeft % 60 === 0) {
            elements.hintAudio.play().catch(e => console.log('提示音播放失败:', e));
        }
    }, 1000);
}

function submitExam() {
    clearInterval(examTimerInterval);

    // 计算分数
    let correctCount = 0;
    examQuestions.forEach((q, i) => {
        if (userAnswers[i] === q.answer.toLowerCase()) {
            correctCount++;
        }
    });

    const score = Math.round((correctCount / examQuestions.length) * 100);
    const endTime = new Date();
    const timeUsed = Math.floor((endTime - examStartTime) / 1000);
    const minutes = Math.floor(timeUsed / 60);
    const seconds = timeUsed % 60;

    // 更新结果
    document.getElementById('exam-score').textContent = score;
    document.getElementById('exam-correct-count').textContent = correctCount;
    document.getElementById('exam-time-used').textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

    // 分类统计
    const categoryStats = {};
    examQuestions.forEach(q => {
        if (!categoryStats[q.category]) {
            categoryStats[q.category] = { total: 0, correct: 0 };
        }
        categoryStats[q.category].total++;
    });

    userAnswers.forEach((answer, i) => {
        const q = examQuestions[i];
        if (answer === q.answer.toLowerCase()) {
            categoryStats[q.category].correct++;
        }
    });

    // 渲染分析
    elements.examAnalysisContainer.innerHTML = '';
    for (const category in categoryStats) {
        const { total, correct } = categoryStats[category];
        const percentage = Math.round((correct / total) * 100);

        elements.examAnalysisContainer.innerHTML += `
            <div>
                <div class="flex justify-between mb-1">
                    <span class="font-medium">${category} (${correct}/${total})</span>
                    <span>${percentage}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-primary h-2 rounded-full" style="width: ${percentage}%"></div>
                </div>
            </div>
        `;
    }

    // 显示结果
    elements.examModal.classList.add('hidden');
    elements.examResultModal.classList.remove('hidden');
}

function reviewExam() {
    // 渲染所有题目及解析
    const questionsHtml = examQuestions.map((q, i) => {
        const userAnswer = userAnswers[i];
        const isCorrect = userAnswer === q.answer.toLowerCase();
        const cardClass = isCorrect ? 'correct' : 'incorrect';

        const optionsHtml = q.options.map((option, j) => {
            const optionLetter = String.fromCharCode(97 + j);
            const isSelected = userAnswer === optionLetter;
            const isAnswer = q.answer.toLowerCase() === optionLetter;

            let optionClass = '';
            if (isAnswer) optionClass = 'correct';
            else if (isSelected) optionClass = 'incorrect';

            return `
                <div class="option-item p-4 rounded-lg border border-gray-200 mb-3 ${optionClass} ${isSelected ? 'selected' : ''}">
                    ${optionLetter}) ${option}
                    ${isAnswer ? '<i class="fa fa-check ml-2 text-green-500"></i>' : ''}
                    ${!isAnswer && isSelected ? '<i class="fa fa-times ml-2 text-red-500"></i>' : ''}
                </div>
            `;
        }).join('');

        return `
            <div class="question-card ${cardClass} bg-white rounded-xl p-6 shadow-sm mb-6">
                <div class="flex items-start mb-5">
                    <div class="w-8 h-8 ${isCorrect ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'} rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                        ${i + 1}
                    </div>
                    <div class="font-medium text-lg">${q.question}</div>
                </div>
                <div class="options-container ml-11">
                    ${optionsHtml}
                </div>
                <div class="explanation mt-4 ml-11 bg-blue-50 p-4 rounded-lg show">
                    <div class="font-medium text-blue-700 mb-2">
                        <i class="fa fa-lightbulb-o mr-2"></i>解析
                    </div>
                    <div>${q.explanation || '暂无解析'}</div>
                </div>
            </div>
        `;
    }).join('');

    elements.examQuestionsContainer.innerHTML = questionsHtml;
    elements.examResultModal.classList.add('hidden');
    elements.examModal.classList.remove('hidden');

    // 更新按钮
    elements.examPrevBtn.classList.add('hidden');
    elements.examNextBtn.classList.add('hidden');
    elements.examSubmitBtn.classList.add('hidden');

    // 添加返回按钮
    const footerContainer = document.querySelector('#exam-modal .p-6.border-t');
    const backButton = document.createElement('button');
    backButton.id = 'exam-back-to-result';
    backButton.className = 'px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors';
    backButton.innerHTML = '<i class="fa fa-arrow-left mr-2"></i>返回结果';
    footerContainer.appendChild(backButton);

    // 返回按钮事件
    backButton.addEventListener('click', () => {
        backButton.remove();
        elements.examModal.classList.add('hidden');
        elements.examResultModal.classList.remove('hidden');
    });

    // 更新页码
    document.querySelector('#exam-current-question-number').parentElement.innerHTML = `
        <div class="text-primary font-medium">
            <i class="fa fa-check-circle mr-1"></i>笔试结果详情
        </div>
    `;
}

function continueToInterview() {
    elements.examResultModal.classList.add('hidden');
    startActualInterview();
}

// ================== 方向选择与简历上传 ==================
function confirmDirectionSelection() {
    if (!selectedDirection) return;

    // 获取面试问题
    fetch('/get_q/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: JSON.stringify({ direction: selectedDirection })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('请求失败');
        }
        return response.json();
    })
    .then(data => {
        console.log('获取问题成功:', data);
        if (data.questions && Array.isArray(data.questions) && data.questions.length > 0) {
            // 从后端获取的问题中随机选择3个
            randomQuestions = getRandomQuestions(
                data.questions.map(q => q.question_text),
                3
            );
        } else {
            // 后端问题不足时使用预设问题
            randomQuestions = getRandomQuestions(questionPool[selectedDirection], 3);
        }

        // 显示上传模态框
        elements.directionModal.classList.add('hidden');
        elements.selectedDirectionEl.textContent = `已选择: ${selectedDirection}`;
        elements.selectedDirectionEl.classList.remove('hidden');
        elements.resumeUploadModal.classList.remove('hidden');
    })
    .catch(error => {
        console.error('获取问题失败:', error);
        // 完全依赖预设问题
        randomQuestions = getRandomQuestions(questionPool[selectedDirection], 3);
        elements.directionModal.classList.add('hidden');
        elements.selectedDirectionEl.textContent = `已选择: ${selectedDirection}`;
        elements.selectedDirectionEl.classList.remove('hidden');
        elements.resumeUploadModal.classList.remove('hidden');
    });
}

function resetDirectionSelection() {
    elements.directionCards.forEach(c => {
        c.classList.remove('border-primary', 'bg-primary/5');
        c.classList.add('border-gray-200');
    });
    selectedDirection = '';
    elements.confirmDirectionBtn.disabled = true;
    elements.confirmDirectionBtn.classList.add('opacity-50', 'cursor-not-allowed');
}

function handleResumeSelection(e) {
    if (e.target.files.length > 0) {
        elements.confirmUpload.disabled = false;
        elements.confirmUpload.classList.remove('opacity-50', 'cursor-not-allowed');

        const fileName = e.target.files[0].name;
        elements.uploadStatus.textContent = `已选择: ${fileName}`;
        elements.uploadStatus.classList.remove('text-gray-500');
        elements.uploadStatus.classList.add('text-green-600');
    } else {
        elements.confirmUpload.disabled = true;
        elements.confirmUpload.classList.add('opacity-50', 'cursor-not-allowed');
    }
}

function resetUploadState() {
    elements.resumeUpload.value = '';
    elements.confirmUpload.disabled = true;
    elements.confirmUpload.classList.add('opacity-50', 'cursor-not-allowed');
    elements.uploadProgress.classList.add('hidden');
    elements.resumeProgressBar.style.width = '0%';
    elements.uploadStatus.textContent = '上传中...';
    elements.uploadStatus.classList.remove('text-green-600', 'text-red-600');
    elements.uploadStatus.classList.add('text-gray-500');
    elements.selectedDirectionEl.classList.add('hidden');
}

function uploadResume() {
    if (elements.resumeUpload.files.length === 0) return;

    elements.uploadProgress.classList.remove('hidden');

    const file = elements.resumeUpload.files[0];
    const formData = new FormData();
    formData.append('avatar', file);
    formData.append('direction', selectedDirection);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/pic/', true);
    xhr.setRequestHeader('X-CSRFToken', csrftoken);

    xhr.upload.addEventListener('progress', (e) => {
        if (e.lengthComputable) {
            const percent = Math.round((e.loaded / e.total) * 100);
            elements.resumeProgressBar.style.width = `${percent}%`;
            elements.uploadStatus.textContent = `上传中... ${percent}%`;
        }
    });

    xhr.addEventListener('load', () => {
        if (xhr.status >= 200 && xhr.status < 300) {
            elements.uploadStatus.textContent = '上传完成！即将开始笔试...';
            elements.uploadStatus.classList.remove('text-gray-500');
            elements.uploadStatus.classList.add('text-green-600');

            setTimeout(() => {
                elements.resumeUploadModal.classList.add('hidden');
                resetUploadState();
                elements.examModal.classList.remove('hidden');
                initExam();
            }, 1500);
        } else {
            elements.uploadStatus.textContent = '上传失败，请重试';
            elements.uploadStatus.classList.remove('text-gray-500');
            elements.uploadStatus.classList.add('text-red-600');
        }
    });

    xhr.addEventListener('error', () => {
        elements.uploadStatus.textContent = '网络错误，请重试';
        elements.uploadStatus.classList.remove('text-gray-500');
        elements.uploadStatus.classList.add('text-red-600');
    });

    xhr.send(formData);
}

// ================== 辅助函数 ==================
function switchToQuestionVideo() {
    elements.interviewerListeningVideo.classList.add('hidden');
    elements.interviewerVideo.classList.remove('hidden');
    elements.interviewerListeningStatus.classList.add('hidden');
    elements.interviewerStatus.classList.remove('hidden');

    elements.interviewerVideo.currentTime = 0;
    elements.interviewerVideo.play();
}

function switchToListeningVideo() {
    elements.interviewerVideo.classList.add('hidden');
    elements.interviewerListeningVideo.classList.remove('hidden');
    elements.interviewerStatus.classList.add('hidden');
    elements.interviewerListeningStatus.classList.remove('hidden');

    elements.interviewerListeningVideo.currentTime = 0;
    elements.interviewerListeningVideo.play();
}

function playCurrentQuestion() {
    if (currentQuestionIndex >= randomQuestions.length) return;

    const questionText = randomQuestions[currentQuestionIndex];

    elements.questionAudios.forEach(audio => {
        audio.pause();
        audio.currentTime = 0;
    });

    // 切换到提问视频
    switchToQuestionVideo();

    const audioIndex = currentQuestionIndex % elements.questionAudios.length;
    elements.questionAudios[audioIndex].play();

    // 播放问题语音
    speakText(questionText, () => {
        switchToListeningVideo();
        elements.startAnswerBtn.disabled = false;
        elements.startAnswerBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        speechSynthesisInProgress = false;
    });

    document.getElementById('current-question').textContent = questionText;
    speechSynthesisInProgress = true;
}

function updateTimer() {
    if (!interviewStartTime) return;

    const now = new Date();
    const elapsedSeconds = Math.floor((now - interviewStartTime) / 1000);
    const minutes = Math.floor(elapsedSeconds / 60);
    const seconds = elapsedSeconds % 60;

    document.getElementById('modal-duration').textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
}

function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
}

function handleScroll() {
    const nav = document.getElementById('main-nav');
    if (window.scrollY > 10) {
        nav.classList.add('bg-white', 'shadow-md');
        nav.classList.remove('py-4');
        nav.classList.add('py-2');
    } else {
        nav.classList.remove('bg-white', 'shadow-md');
        nav.classList.remove('py-2');
        nav.classList.add('py-4');
    }
}

// 页面加载完成后初始化语音
window.addEventListener('load', initVoiceSelection);


</script>
</body>
</html>